<template>
  <div class="order-list">
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="listLoading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div 
          v-for="order in displayOrders" 
          :key="order.id" 
          class="order-item"
          @click="viewOrderDetail(order)"
        >
          <!-- 订单头部 -->
          <div class="order-header">
            <div class="order-info">
              <span class="order-no">订单号：{{ order.orderNo }}</span>
              <span class="order-type" :class="getOrderTypeClass(order.type)">
                {{ getOrderTypeText(order.type) }}
              </span>
            </div>
            <div class="order-status" :class="getStatusClass(order.status)">
              {{ getStatusText(order.status) }}
            </div>
          </div>
          
          <!-- 商品信息 -->
          <div class="goods-info">
            <div 
              v-for="item in order.snapItems" 
              :key="item.id" 
              class="goods-item"
            >
              <img :src="item.img" :alt="item.title" class="goods-image" />
              <div class="goods-details">
                <div class="goods-title">{{ item.title }}</div>
                <div class="goods-specs" v-if="item.specs">
                  {{ formatSpecs(item.specs) }}
                </div>
                <div class="goods-price">
                  <span class="price">¥{{ formatPrice(item.price) }}</span>
                  <span class="count">x{{ item.count }}</span>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 订单金额 -->
          <div class="order-amount">
            <div class="amount-item">
              <span>商品总价：</span>
              <span>¥{{ formatPrice(order.totalPrice) }}</span>
            </div>
            <div v-if="order.finalTotalPrice !== order.totalPrice" class="amount-item">
              <span>实付金额：</span>
              <span class="final-price">¥{{ formatPrice(order.finalTotalPrice) }}</span>
            </div>
            <div v-if="order.type === 'points'" class="amount-item">
              <span>使用积分：</span>
              <span class="points-used">{{ getPointsUsed(order) }} 积分</span>
            </div>
          </div>
          
          <!-- 订单时间 -->
          <div class="order-time">
            <span>下单时间：{{ formatTime(order.placedTime) }}</span>
          </div>
          
          <!-- 操作按钮 -->
          <div class="order-actions">
            <van-button 
              v-if="order.status === 'delivered'" 
              type="primary" 
              size="small"
              @click.stop="confirmReceive(order)"
            >
              确认收货
            </van-button>
            <van-button 
              v-if="canPublishSecondhand(order)" 
              type="success" 
              size="small"
              @click.stop="publishSecondhand(order)"
            >
              发布二手
            </van-button>
            <van-button 
              type="default" 
              size="small"
              @click.stop="viewOrderDetail(order)"
            >
              查看详情
            </van-button>
          </div>
        </div>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'
import { confirmReceiveOrder } from '@/api/order'

const props = defineProps({
  orders: {
    type: Array,
    default: () => []
  },
  loading: {
    type: Boolean,
    default: false
  }
})

const router = useRouter()

// 响应式数据
const refreshing = ref(false)
const listLoading = ref(false)
const finished = ref(false)
const page = ref(1)
const pageSize = 10

// 计算属性
const displayOrders = computed(() => {
  const start = (page.value - 1) * pageSize
  const end = start + pageSize
  return props.orders.slice(start, end)
})

// 监听订单数据变化
watch(() => props.orders, (newOrders) => {
  if (newOrders.length === 0) {
    finished.value = true
  } else {
    finished.value = newOrders.length <= pageSize
  }
}, { immediate: true })

// 获取订单类型样式类
const getOrderTypeClass = (type) => {
  const classMap = {
    'points': 'type-points',
    'vip': 'type-vip',
    'normal': 'type-normal'
  }
  return classMap[type] || 'type-default'
}

// 获取订单类型文本
const getOrderTypeText = (type) => {
  const textMap = {
    'points': '积分订单',
    'vip': '二手订单',
    'normal': '普通订单'
  }
  return textMap[type] || '未知类型'
}

// 获取状态样式类
const getStatusClass = (status) => {
  const classMap = {
    'paid': 'status-paid',
    'confirmed': 'status-confirmed',
    'delivered': 'status-delivered',
    'completed': 'status-completed'
  }
  return classMap[status] || 'status-default'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'paid': '已支付',
    'confirmed': '已确认',
    'delivered': '已发货',
    'completed': '已完成'
  }
  return textMap[status] || '未知状态'
}

// 格式化规格
const formatSpecs = (specs) => {
  if (!specs || !Array.isArray(specs)) return ''
  return specs.map(spec => `${spec.key}: ${spec.value}`).join(', ')
}

// 格式化价格
const formatPrice = (price) => {
  if (!price) return '0.00'
  return Number(price).toFixed(2)
}

// 获取使用的积分
const getPointsUsed = (order) => {
  if (order.type !== 'points') return 0
  // 假设1元=10积分
  const discount = order.totalPrice - order.finalTotalPrice
  return Math.floor(discount * 10)
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString('zh-CN')
}

// 查看订单详情
const viewOrderDetail = (order) => {
  router.push({
    path: '/my-purchases/detail',
    query: { id: order.id }
  })
}

// 判断是否可以发布二手
const canPublishSecondhand = (order) => {
  // 二手订单：已确认状态可以发布
  if (order.type === 'vip' && order.status === 'confirmed') {
    return true
  }
  // 普通订单：已完成状态可以发布
  if (order.type === 'normal' && order.status === 'completed') {
    return true
  }
  // 积分订单：已支付状态可以发布
  if (order.type === 'points' && order.status === 'paid') {
    return true
  }
  return false
}

// 发布二手
const publishSecondhand = (order) => {
  // 计算建议价格（按购买支付金额）
  const suggestedPrice = order.finalTotalPrice || order.totalPrice
  
  // 根据订单类型显示不同的提示
  let title = '二手商品'
  if (order.type === 'vip') {
    title = '二手商品'
  } else if (order.type === 'points') {
    title = '积分商品'
  } else if (order.type === 'normal') {
    title = '普通商品'
  }
  
  // 跳转到二手发布页面，传递商品信息
  router.push({
    path: '/vip-order',
    query: {
      fromOrder: order.id,
      suggestedPrice: suggestedPrice,
      productInfo: JSON.stringify({
        title: order.snapTitle || title,
        image: order.snapImg,
        specs: order.snapItems
      })
    }
  })
}

// 确认收货
const confirmReceive = async (order) => {
  try {
    await showConfirmDialog({
      title: '确认收货',
      message: '确认已收到商品？'
    })
    
    const response = await confirmReceiveOrder(order.id)
    if (response.success) {
      showToast('确认收货成功')
      // 刷新订单状态
      order.status = 'completed'
    } else {
      showToast(response.message || '确认收货失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认收货失败:', error)
      showToast('确认收货失败')
    }
  }
}

// 下拉刷新
const onRefresh = async () => {
  page.value = 1
  finished.value = false
  refreshing.value = false
}

// 上拉加载
const onLoad = () => {
  if (props.orders.length > page.value * pageSize) {
    page.value++
  } else {
    finished.value = true
  }
  listLoading.value = false
}
</script>

<style lang="scss" scoped>
.order-list {
  padding: 12px;
}

.order-item {
  background: linear-gradient(135deg, #ffffff 0%, #fafbfc 100%);
  border-radius: 12px;
  margin-bottom: 12px;
  padding: 18px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f2f5;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  }
  
  .order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #e9ecef;
    
    .order-info {
      .order-no {
        font-size: 13px;
        color: #495057;
        margin-right: 12px;
        font-weight: 500;
      }
      
      .order-type {
        font-size: 12px;
        padding: 4px 10px;
        border-radius: 20px;
        color: #fff;
        font-weight: 500;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        
        &.type-points {
          background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
        }
        
        &.type-vip {
          background: linear-gradient(135deg, #157658 0%, #0f5a3f 100%);
        }
        
        &.type-normal {
          background: linear-gradient(135deg, #4a90e2 0%, #357abd 100%);
        }
        
        &.type-default {
          background: linear-gradient(135deg, #95a5a6 0%, #7f8c8d 100%);
        }
      }
    }
    
    .order-status {
      font-size: 14px;
      font-weight: 600;
      padding: 4px 12px;
      border-radius: 20px;
      
      &.status-paid {
        color: #07c160;
        background: rgba(7, 193, 96, 0.1);
      }
      
      &.status-confirmed {
        color: #ff976a;
        background: rgba(255, 151, 106, 0.1);
      }
      
      &.status-delivered {
        color: #1989fa;
        background: rgba(25, 137, 250, 0.1);
      }
      
      &.status-completed {
        color: #157658;
        background: rgba(21, 118, 88, 0.1);
      }
      
      &.status-default {
        color: #95a5a6;
        background: rgba(149, 165, 166, 0.1);
      }
    }
  }
  
  .goods-info {
    margin-bottom: 16px;
    
    .goods-item {
      display: flex;
      margin-bottom: 12px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .goods-image {
        width: 70px;
        height: 70px;
        object-fit: cover;
        border-radius: 10px;
        margin-right: 14px;
        border: 2px solid #f8f9fa;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
      }
      
      .goods-details {
        flex: 1;
        
        .goods-title {
          font-size: 15px;
          color: #2c3e50;
          margin-bottom: 6px;
          line-height: 1.4;
          font-weight: 600;
        }
        
        .goods-specs {
          font-size: 12px;
          color: #6c757d;
          margin-bottom: 6px;
          font-weight: 500;
        }
        
        .goods-price {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .price {
            font-size: 15px;
            color: #e74c3c;
            font-weight: bold;
          }
          
          .count {
            font-size: 12px;
            color: #7f8c8d;
            font-weight: 500;
          }
        }
      }
    }
  }
  
  .order-amount {
    margin-bottom: 16px;
    padding: 14px;
    background: linear-gradient(135deg, #f8f9fa 0%, #f1f3f4 100%);
    border-radius: 10px;
    border: 1px solid #e9ecef;
    
    .amount-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
      font-size: 14px;
      color: #495057;
      font-weight: 500;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .final-price {
        color: #e74c3c;
        font-weight: bold;
      }
      
      .points-used {
        color: #157658;
        font-weight: bold;
      }
    }
  }
  
  .order-time {
    margin-bottom: 16px;
    font-size: 12px;
    color: #6c757d;
    padding: 8px 12px;
    background: rgba(108, 117, 125, 0.05);
    border-radius: 8px;
    text-align: center;
    font-weight: 500;
  }
  
  .order-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    
    .van-button {
      min-width: 80px;
      border-radius: 8px;
      font-weight: 500;
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-1px);
      }
    }
  }
}
</style> 